<?php


namespace App\Logic\Account\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Logic\Member\MemberScoreService;
use App\Model\Account\RechargeModel;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberScoreModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Validate\Exception\Runtime;

class ConfirmRechargeForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $score;
    public $remark;
    public $password;
    public $created_at;
    public $_rechargeModel;


    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'password' => ['required', '密码', '密码错误'],
            'id'      => ['required|integer', '充值ID', '充值ID错误'],
            'score'   => ['required|numeric', '代币', '代币错误'],
        ];
    }

    /**
     * @throws Runtime
     * @throws Exception
     * @throws \Throwable
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        /**判断充值记录是否存在*/
        if (!$this->_rechargeModel = RechargeModel::create()->getOne(['id' => $this->id])) {
            throw new DefaultException('充值记录不存在', 600);
        }
        /**判断充值记录状态是否为 RechargeModel::INPROGRESS*/
        if ($this->_rechargeModel->recharge_state != RechargeModel::INPROGRESS) {
            throw new DefaultException('充值记录状态错误', 600);
        }
        /**判断密码是否正确*/
        if(!UserIdentityHelper::validatePassword($this->password)){
            throw new DefaultException('密码错误', 600);
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {

            /**读取充值记录并且锁定*/
            $recharge = RechargeModel::create()->connection('write')->lockForUpdate()->getOne(['id' => $this->id]);
            $this->user_id = $recharge->user_id;
            /**更新充值记录状态为 RechargeModel::FINISHED*/
            $rechargeData = [
                'recharge_state' => RechargeModel::FINISHED,
                'score'          => bcmul($this->score, 1, 2),
                'payment_state'  => RechargeModel::PAID,
                'remark'         => $this->remark,
            ];
            RechargeModel::create()->updateData($rechargeData, ['id' => $this->id]);

            MemberScoreService::getInstance()->change($this->user_id, $this->score, MemberScoreModel::TYPE_RECHARGE, $this->id, '充值');
//            /**MemberModel 通过$this->user_id获取到用户信息,并且lockForUpdate*/
//            $member = MemberModel::create()->connection('write')->lockForUpdate()->getOne(['id' => $this->user_id]);
//            /**将充值代币score更新到ss_member中 MemberModel*/
//            $memberData = [
//                'score' => bcadd($member->score, $this->score, 2),
//            ];
//
//            MemberModel::create()->updateData($memberData, ['id' => $this->user_id]);
//
//            /**MemberScoreModel 将score的变动记录添加到ss_member_score中*/
//            $data = [
//                'user_id'      => $this->user_id,
//                'score'        => bcmul($this->score, 1, 2),
//                'before_score' => $member->score,
//                'after_score'  => bcadd($member->score, $this->score, 2),
//                'created_date' => date('Y-m-d'),
//                'remark'       => '充值代币',
//                'type'         => MemberScoreModel::TYPE_RECHARGE,
//                'object_id'    => $this->id
//            ];
//            MemberScoreModel::create()->insertData($data);

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $this->id];

            $result = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }
}
